package com.donfu.web.controller.wxhouse;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.donfu.common.annotation.Log;
import com.donfu.common.core.controller.BaseController;
import com.donfu.common.core.domain.AjaxResult;
import com.donfu.common.core.page.TableDataInfo;
import com.donfu.common.enums.BusinessType;
import com.donfu.common.utils.StringUtils;
import com.donfu.system.domain.house.HouseUser;
import com.donfu.system.domain.house.HouseUserVip;
import com.donfu.system.service.house.IHouseUserService;
import com.donfu.system.service.house.IHouseUserVipService;
import com.donfu.web.controller.tool.MapHelper;
import com.donfu.web.controller.tool.WxChatConfig;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息Controller
 * 
 * @author 曹雨心
 * @date 2021-12-01
 */
@RestController
@RequestMapping("/wx/house/user")
public class WebHouseUserController extends BaseController
{
    @Autowired
    private IHouseUserService houseUserService;

    @Autowired
    private IHouseUserVipService houseUserVipService;
    /**
     * 获取用户信息详细信息
     */
    @ApiOperation("查看详细信息")
    //@PreAuthorize("@ss.hasPermi('house:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(houseUserService.selectHouseUserById(id));
    }

    /**
     * 获取用户邀请列表
     */
    @ApiOperation("获取用户邀请列表")
    @GetMapping("/getInviter")
    public TableDataInfo getInviter(@RequestParam String inviterOpenid)
    {
        startPage();
        List<Map<String,Object>> houseUsers = houseUserService.selectHouseInviterUserList(inviterOpenid);
        return getDataTable(houseUsers);
    }

    /**
     * 用户修改信息
     */
    @ApiOperation("修改用户信息")
   // @PreAuthorize("@ss.hasPermi('house:user:edit')")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HouseUser houseUser)
    {
        houseUser.setUpdateDate(new Date());
        return toAjax(houseUserService.updateHouseUser(houseUser));
    }

    /**
     * 添加会员
     * @param userVip
     * @return
     */
    @ApiOperation("添加会员")
    @PostMapping("/addVip")
    public AjaxResult addUserVip(@RequestBody HouseUserVip userVip){
        AjaxResult ajaxResult = checkHouseUserVip(userVip);
        String code = ajaxResult.get("code").toString();
        if(code.contains("50")){
            return ajaxResult;
        }
        // 实质上，这个userId应该从token中解析出来，而不是像这样直接封装进HouseUserVip
        Long userId = userVip.getUserId();

        HouseUserVip houseUserVip=new HouseUserVip();
        houseUserVip.setUserId(userId);
        // 再次查询数据库中是否存在这个用户的数据
        List<HouseUserVip> list = houseUserVipService.selectHouseUserVipList(houseUserVip);
        if(list!=null && list.size()>0){
            return AjaxResult.error("此用户已申请过会员");
        }
        // 将审批状态设置为 审核中
        userVip.setIsAllow(0);
        userVip.setUserId(userId);
        userVip.setCreateDate(new Date());
        int i = houseUserVipService.insertHouseUserVip(userVip);
        return toAjax(i);
    }

    /**
     * 查看此用户的会员状态
     * @param userId
     * @return
     */
    @ApiOperation("查看此用户的会员状态")
    @GetMapping("/getVip")
    public AjaxResult findUserVip(Long userId){
        HouseUserVip userVip=new HouseUserVip();
        userVip.setUserId(userId);
        List<HouseUserVip> houseUserVips = houseUserVipService.selectHouseUserVipList(userVip);
        if(houseUserVips!=null && houseUserVips.size()>0){
            return AjaxResult.success(houseUserVips.get(0));
        }
        return AjaxResult.success();

    }

    /**
     * 根据用户id和会员id删除会员信息，只有审核不通过才能删除
     * @param userId
     * @param id
     * @return
     */
    @ApiOperation("删除会员信息")
    @DeleteMapping("/deleteVip")
    public AjaxResult deleteUserVip(Long userId,Long id){
        HouseUserVip userVip = houseUserVipService.selectHouseUserVipById(id);
        if(userVip==null || userVip.getIsAllow()!=2){
            return AjaxResult.error("只有审核不通过才能删除");
        }
        int i = houseUserVipService.deleteHouseUserVipByIdAndUserId(id, userId);
        return toAjax(i);
    }

    public AjaxResult checkHouseUserVip(HouseUserVip userVip){
        String realName = userVip.getRealName();
        if(realName==null || realName.equals("")){
            return AjaxResult.error("会员姓名不能为空");
        }
        if(realName.length()>100){
            return AjaxResult.error("会员姓名长度过长");
        }
        Integer sex = userVip.getSex();
        if(sex==null){
            return AjaxResult.error("性别不能为空");
        }
        if (sex!=1 && sex!=2){
            return AjaxResult.error("请正常的选择性别");
        }
        String userPhone = userVip.getUserPhone();
        if(userPhone==null){
            return AjaxResult.error("手机号码不能为空");
        }
        String regexPhone = "^(1[0-9])\\d{9}$";
        boolean matches = userPhone.matches(regexPhone);
        if (!matches) {
            return AjaxResult.error("手机号码格式不正确");
        }

        return AjaxResult.success();
    }
    /*
    * @作者 覃创斌
    * @描述 微信授权登录
    * @日期 2021/12/11
    **/
    @PostMapping("/authorizationLogin")
    public AjaxResult authorizationLogin(@RequestParam(name = "wxCode")  String wxCode){
        String requestUrl = WxChatConfig.getUrl() + "sns/jscode2session";
        Map<String,Object> requestUrlParam = new HashMap<String,Object>();
        requestUrlParam.put("appid", WxChatConfig.getAppid());	//小程序 appId
        requestUrlParam.put("secret", WxChatConfig.getSecret());	//小程序 appSecret
        requestUrlParam.put("js_code", wxCode);	//登录时获取的 code
        requestUrlParam.put("grant_type", "authorization_code");	//授权类型，此处固定
        JSONObject jsonObject = JSON.parseObject(HttpUtil.get(requestUrl,requestUrlParam));
        String openid = jsonObject.getString("openid");
        if (openid.length() > 0){
            return AjaxResult.success(jsonObject);
        }else {
            return AjaxResult.error("授权失败");
        }

    }

    @PostMapping("/authLoginUpdateData")
    public AjaxResult authLoginUpdateData(@RequestParam(name = "wxOpenid")  String wxOpenid,
                                          @RequestParam(name = "wxSessionKey")  String wxSessionKey,
                                          @RequestParam(name = "wxHeadUrl")  String wxHeadUrl,
                                          @RequestParam(name = "wxNickName")  String wxNickName,
                                          @RequestParam(name = "wxGender")  Integer wxGender
    ){
        HouseUser houseUser = houseUserService.selectHouseUserByOpenid(wxOpenid);
        if (StringUtils.isNotNull(houseUser)){
            houseUser.setSessionKey(wxSessionKey);
            houseUser.setSex(wxGender);
            houseUser.setWxNickName(wxNickName);
            houseUser.setWxHeadUrl(wxHeadUrl);
            houseUser.setStatus(0);
            houseUserService.updateHouseUser(houseUser);
        }else {
            houseUser.setWeixinOpenid(wxOpenid);
            houseUser.setSex(wxGender);
            houseUser.setWxNickName(wxNickName);
            houseUser.setWxHeadUrl(wxHeadUrl);
            houseUser.setSessionKey(wxSessionKey);
            houseUser.setStatus(0);
            houseUserService.insertHouseUser(houseUser);
        }
        return AjaxResult.success("登录成功！").put("userId",houseUser.getId());
    }

    /**
     * 根据经纬度获取所在城市
     * @param longitude
     * @param latitude
     * @return
     */
    @ApiOperation("根据经纬度获取所在城市")
    @GetMapping("/getCityByDu")
    public AjaxResult getCityByLongAndLat(String longitude,String latitude){
        if(longitude==null || latitude==null || "".equals(latitude)|| "".equals(longitude)){
            return AjaxResult.success();
        }
        JSONObject province = MapHelper.getAddressInfoByLngAndLat(longitude, latitude);
       return  AjaxResult.success(province);
    }

}
